package project.tool4nat.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import project.tool4nat.common.Config;
import project.tool4nat.common.DataPackDecoder;
import project.tool4nat.common.DataPackEncoder;
import project.tool4nat.common.Starter;
import project.tool4nat.server.handler.CallerHandler;
import project.tool4nat.server.handler.ServerTunnelHandler;

public class ServerStarter implements Starter {

    private final static Logger logger = LoggerFactory.getLogger(ServerStarter.class);

    private EventLoopGroup worker;

    private EventLoopGroup boss;


    public ServerStarter() {
        worker = new NioEventLoopGroup();
        boss = new NioEventLoopGroup();
    }

    public void openNatServer() throws InterruptedException {
        logger.info("nat server started on port {}", Config.SERVER_PORT);
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new DataPackDecoder(1024 * 1024 * 3, 0, 4))
                                .addLast(new DataPackEncoder())
                                .addLast(new ServerTunnelHandler());
                    }
                })
                .bind(Config.SERVER_PORT)
                .sync()
                .channel()
                .closeFuture()
                .sync();
    }

    public void openCallerServer() throws InterruptedException {
        logger.info("listening request from port {}", Config.CALLER_PORT);
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new CallerHandler());
                    }
                })
                .bind(Config.CALLER_PORT)
                .sync()
                .channel()
                .closeFuture()
                .sync();
    }

    @Override
    public void startup() throws Exception {
        new Thread(() -> {
            try {
                openNatServer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                shutdown();
            }
        }).start();
        openCallerServer();
    }

    @Override
    public void shutdown() {
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }

    public static void main(String[] args) {
        Starter starter = new ServerStarter();
        try {
            starter.startup();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            starter.shutdown();
        }
    }

}
